#include <string.h>
#include <iostream>

using std::cout;
using std::endl;

class String
{
public:
    //无参构造函数
	String()
    : _pstr(nullptr)
    {
        cout << "String()" << endl;
    }

    //C风格字符串
    //n + shift + k(n代表的是数字1 2 3 4)
	String(const char *pstr)
    : _pstr(new char[strlen(pstr) + 1]())
    {
        cout << "String(const char *)" << endl;
        strcpy(_pstr, pstr);
    }

    //拷贝构造函数
	String(const String &rhs)
    : _pstr(new char[strlen(rhs._pstr) + 1]())
    {
        cout << "String(const String &)" << endl;
        strcpy(_pstr, rhs._pstr);
    }

    //赋值运算符函数
	String &operator=(const String &rhs)
    {
        cout << "String &operator=(const String &)" << endl;
        if(this != &rhs)//1、自赋值
        {
            delete [] _pstr;//2、释放左操作数
            _pstr = nullptr;

            //3、深拷贝
            _pstr = new char[strlen(rhs._pstr) + 1]();
            strcpy(_pstr, rhs._pstr);
        }

        return *this;//4、返回*this
    }

    //析构函数
	~String()
    {
        cout << "~String()" << endl;
        if(_pstr)
        {
            delete [] _pstr;
            _pstr = nullptr;
        }
    }

	void print() const
    {
        if(_pstr)
        {
            cout << "_pstr = " << _pstr << endl;
        }
    }

    //无符号的整形
    size_t length() const
    {
        if(_pstr)
        {
            return strlen(_pstr);
        }
        else
        {
            return 0;
        }
    }

    const char * c_str() const
    {
        return _pstr;
    }

private:
	char *_pstr;
};

int main()
{
	String str1;
	str1.print();
	
    cout << endl << "C风格的构造函数" << endl;
    //临时对象的创建、拷贝、析构
    //int a = 10;
    //int b = 10.23;
	String str2 = "Hello,world";//String("Hello,world")
	String str3("wangdao");
	
	str2.print();		
	str3.print();	
	
    cout << endl << "拷贝构造函数" << endl;
	String str4 = str3;
	str4.print();
	
    /* cout << endl << endl; */
    cout << endl << "赋值运算符函数" << endl;
	str4 = str2;
	str4.print();

    cout << endl;
    printf("&str4 = %p\n", &str4);
    printf("str4.c_str() = %p\n", str4.c_str());

    //String--->const char *
    const char *pstr = str4.c_str();
	
	return 0;
}

